package com.allwees.core.event.aop;

import com.allwees.core.common.parser.el.ExpressionParser;
import com.allwees.core.event.interceptor.LocalEventOperationInvoker;
import com.allwees.core.event.interceptor.LocalEventSupport;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

@Slf4j
@Aspect
public class LocalEventAop extends LocalEventSupport {

    private ExpressionParser parser;

    @Pointcut("@annotation(com.allwees.core.event.annotation.LocalEvent) " +
            "|| @annotation(com.allwees.core.event.annotation.LocalEvents)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object invoke(final ProceedingJoinPoint pjp) throws Throwable {
        LocalEventOperationInvoker aopAllianceInvoker = () -> {
            try {
                return pjp.proceed();
            } catch (Throwable ex) {
                throw new LocalEventOperationInvoker.ThrowableWrapper(ex);
            }
        };

        try {
            return execute(aopAllianceInvoker,
                    pjp.getThis(),
                    ((MethodSignature) pjp.getSignature()).getMethod(),
                    pjp.getArgs());
        } catch (LocalEventOperationInvoker.ThrowableWrapper th) {
            throw th.getOriginal();
        }
    }

    public LocalEventAop setParser(ExpressionParser parser){
        this.parser = parser;
        return this;
    }

    @Override
    protected ExpressionParser getParser() {
        return parser;
    }
}
